# -*- coding:utf-8 -*-
from API import *
import sys

USER = MyJson(filename='USER.json')  # 测试用USER列表
SET = MyJson(filename='SET.json')  # 测试用SET列表


def login(**kwargs):
    JSON = {}
    try:
        if kwargs['password'] == USER.object[kwargs['user_id']]['password']:
            JSON['return'] = USER.object[kwargs['user_id']]
        else:
            JSON['return'] = False
            JSON['info'] = "Password Error!"
    except KeyError:
        JSON['return'] = False
        JSON['info'] = "No such user!"
    finally:
        return JSON


def create_user(**kwargs):
    JSON = {}
    try:
        user = USER.object[kwargs['user_id']]
        JSON['return'] = False
        JSON['info'] = "User already exists!"
    except KeyError:
        user_id = kwargs['user_id']
        kwargs.pop('user_id')
        USER.object[user_id] = kwargs
        JSON['return'] = True
    finally:
        return JSON


def update_user(**kwargs):
    JSON = {}
    try:
        user = USER.object[kwargs['user_id']]
        user_id = kwargs['user_id']
        kwargs.pop('user_id')
        USER.object[user_id] = kwargs
        JSON['return'] = True
    except KeyError:
        JSON['return'] = False
        JSON['info'] = "No such user!"
    finally:
        return JSON


def all_users():
    JSON = {}
    arr = []
    try:
        for key, value in USER.object.items():
            arr.append(dict({"user_id": key}, **value))
        JSON['return'] = arr
    except Exception, reason:
        JSON['return'] = False
        JSON['info'] = reason
    finally:
        return JSON


def all_sets():
    JSON = {}
    arr = []
    try:
        for key, value in SET.object.items():
            arr.append(dict({"set_id": key}, **value))
        JSON['return'] = arr
    except Exception, reason:
        JSON['return'] = False
        JSON['info'] = reason
    finally:
        return JSON


def delete_user(user_id):
    JSON = {}
    try:
        USER.object.pop(user_id)
        JSON['return'] = True
    except KeyError:
        JSON['return'] = False
        JSON['info'] = "No such user!"
    finally:
        return JSON


def run(json_name):
    ui = MyJson(filename=json_name + ".json")  # 读取UI传来的JSON文件
    func = eval(ui.object['command'])  # 组建函数
    try:
        ret = MyJson(dict=func(**ui.object['argv']))  # 组建参数获取结果
    except KeyError:
        ret = MyJson(dict=func())
    print ret.object
    ret.save("return.json")  # 结果存为JSON文件
    USER.save("USER.json")
    SET.save("SET.json")


if __name__ == '__main__':
    print login(password='admin1', user_id='admin')
